package com.atguigu.flink0624.chapter07;

import com.atguigu.flink0624.bean.WaterSensor;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/11/13 9:27
 */
public class Flink07_Window_Reduce {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        env
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
            })
            .keyBy(WaterSensor::getId)
            .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<WaterSensor>() {
                    @Override
                    public WaterSensor reduce(WaterSensor ws1,
                                              WaterSensor ws2) throws Exception {
                        System.out.println("reduce....");
                        ws1.setVc(ws1.getVc() + ws2.getVc());
                        return ws1;
                    }
                },
                // 会在窗口关闭的时候, 触发计算
                new WindowFunction<WaterSensor, String, String, TimeWindow>() {
                    @Override
                    public void apply(String key,
                                      TimeWindow window,
                                      Iterable<WaterSensor> input,
                                      Collector<String> out) throws Exception {
                        WaterSensor result = input.iterator().next();
                        
                        out.collect(result + "  " + window);
                    }
                }
            )
            .print();
        
        env.execute();
    }
}
/*
sum max min maxBy minBy 都属于增量聚合

reduce
     增量聚合
 */